package com.marchsoft.musicalstore.service;

import com.marchsoft.musicalstore.entity.SelClassAble;
import com.marchsoft.musicalstore.repository.SelClassAbleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 源
 * Date: 2019-11-20
 * Time: 20:50
 */
@Service

public class SelClassAbleSer {
    @Autowired
    SelClassAbleRepository selClassAbleRepository;


    public List<SelClassAble> getClassByTypeLimit(int type, int courseId, int page, int limit){
        Pageable mypage = PageRequest.of(page-1,limit);
        List<SelClassAble> byTypeAndCourseId;
        if(courseId==0){
            byTypeAndCourseId = selClassAbleRepository.findByType(type, mypage);
        }else{
            byTypeAndCourseId = selClassAbleRepository.findByTypeAndCourseId(type, courseId, mypage);
        }

        return byTypeAndCourseId;
    }



    public Optional<SelClassAble> getOneClass(Integer id){
        Optional<SelClassAble> byId = selClassAbleRepository.findById(id);
        return byId;
    }
    public List<SelClassAble> getCourCatalogue(Integer id) {
        Optional<SelClassAble> oneClass = this.getOneClass(id);
        int teacherId = oneClass.get().getTeacherId();
        return selClassAbleRepository.findByTeacherId(teacherId);
    }



    public List<SelClassAble> getClassAble(String name,int type,int page,int limit,int musicType){
        Sort.Order b = new Sort.Order(Sort.Direction.DESC, "passPeoNum");
        Sort by = Sort.by(b);
        Pageable mypage = PageRequest.of(page-1,limit,by);
        if(name==null){
            return selClassAbleRepository.findAllByOrderByPassPeonumDesc();
        }
        else{
            return selClassAbleRepository.findByNameAndTypeAndCourseId(name,type, mypage,musicType);
        }

    }

    /**
     * 用于保存对象
     * @param selClassAble
     * @return
     */
    public SelClassAble saveSelClass(SelClassAble selClassAble){
        SelClassAble save = selClassAbleRepository.save(selClassAble);
        return save;
    }

}
